<?php
namespace app\controllers;

use app\forms\UserCreateForm;
use app\models\User;
use yii\base\Object;
use app\forms\UserLoginForm;

class UserController extends AjaxController
{
    public function actionCreate(){
        $post = \Yii::$app->getRequest()->post();
        $form = new UserCreateForm();
        $form->setAttributes($post);
        if ($form->validate()) {
            $user = $form->create();
            $data = $user->toArray();
            unset($data['password']);
            unset($data['createTime']);
            return ['data' => $data];
        } else {
            return ['errors' => $form->getErrors()];
        }
    }
    
    public function actionLogin() {
    	$form = new UserLoginForm([
    		'scenario' => UserLoginForm::SCENARIO_LOGIN
    	]);
    	
    	$form->setAttributes(\Yii::$app->request->post());
    	try {
    		$user = $form->login();
    		return ['data' => $user->createAccessToken()];
    	} catch (\app\forms\exceptions\ParamNotValidateException $e) {
    		return ['errors' => $form->getErrors()];
    	} catch (\app\forms\exceptions\LoginFailedException $e) {
    		return ['error' => $e->getCode(), 'message' => $e->getMessage()];
    	}
    }
}

?>